package com.service;

import com.alibaba.fastjson.JSONObject;
import com.dao.ShardingJdbcServiceMapper;
import com.model.UserModel;
import org.apache.commons.lang3.RandomUtils;
import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Service
public class ShardingJdbcService implements IShardingJdbcService {



    @Resource
    private ShardingJdbcServiceMapper shardingJdbcServiceMapper;



    @Override
    public String insert() {
        UserModel um = new UserModel();
        um.setOrderId(RandomUtils.nextInt(10, 10000));
        um.setUserId(RandomUtils.nextInt(10, 10000));
        um.setBusinessId(RandomUtils.nextInt(10, 10000));
//        int num = sqlSession.insert(ShardingJdbcService.class.getName() + ".insert", um);
        int num = shardingJdbcServiceMapper.insert(um);
        JSONObject obj = new JSONObject();
        if (num >= 0) {
            obj.put("code", 0);
            obj.put("msg", "成功");
        } else {
            obj.put("code", 1);
            obj.put("msg", "失败");
        }
        return obj.toJSONString();
    }

    @Override
    public String update(UserModel um) {
        int num = shardingJdbcServiceMapper.update(um);
        JSONObject obj = new JSONObject();
        if (num >= 0) {
            obj.put("code", 0);
            obj.put("msg", "成功");
        } else {
            obj.put("code", 1);
            obj.put("msg", "失败");
        }
        return obj.toJSONString();
    }

    @Override
    public String delete(Integer orderId) {
        int num = shardingJdbcServiceMapper.delete(orderId);
        JSONObject obj = new JSONObject();
        if (num >= 0) {
            obj.put("code", 0);
            obj.put("msg", "成功");
        } else {
            obj.put("code", 1);
            obj.put("msg", "失败");
        }
        return obj.toJSONString();
    }

    @Override
    public String list() {
        List<Map<String, Object>> list= shardingJdbcServiceMapper.orderList();
        JSONObject obj = new JSONObject();
        obj.put("list", list);
        return obj.toJSONString();
    }

    @Override
    public String listById(Integer orderId) {
        UserModel userModel = shardingJdbcServiceMapper.orderById(orderId);
        JSONObject obj = new JSONObject();
        obj.put("userModel", userModel);
        return obj.toJSONString();
    }

}